package org.exteen.tag.core;

import java.io.StringWriter;

import org.exteen.ExteenException;
import org.exteen.exec.ExteenContext;
import org.exteen.exec.Tag;
import org.exteen.output.ExteenStream;
import org.exteen.parser.Attr;
import org.exteen.parser.EscapedString;
import org.exteen.parser.Node;

public class SetTag extends Tag {

    public void doTag(ExteenContext ctx, ExteenStream stream) {

        Node node = ctx.getNode();

        String var = ctx.getVarAttrValue("var");
        if (var==null) {
            throw new ExteenException("Required attribute 'var' missing");
        }

        boolean override = ctx.parseAttributeAsBoolean("override", true);

        Object value = null;
        boolean valueAttrExists = false;

        Attr a = node.getAttribute("value");
        if (a != null) {
            valueAttrExists = true;
            value = a.getValue(ctx);
        }

        if (valueAttrExists && node.getChildren().size()>0) {
            throw new ExteenException("Set tag with 'value' may not have a body");
        }
        if (!valueAttrExists) {
            StringWriter valuewriter = new StringWriter();
            super.doTag(ctx, new ExteenStream(valuewriter));
            value = new EscapedString(valuewriter.toString());
        }

        // here we're setting the value
        ctx.getParent().set(var, value, override); // setInParent()
    }
}